#ifndef WARNINGMANAGE_H
#define WARNINGMANAGE_H

#include <QWidget>
#include <QTableView>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QSqlTableModel>
#include <QSqlError>
#include <QSqlRelationalTableModel>
#include <QSqlQuery>
#include <QMessageBox>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QMap>
#include <QDateTime>
#include <QJSEngine>
#include "sqlitemanage.h"
#include "alarmrecordeditdialog.h"
#include "datareader.h"
#include "logclass.h"

class WarningManage : public QWidget
{
    Q_OBJECT

public:
    explicit WarningManage(QWidget *parent = nullptr);
    ~WarningManage();
    void setUserName(QString &name);
    void processDataPoint(int deviceId, const DataPoint &data);

private slots:
    void addAlarmRule();
    void deleteAlarmRule();
    void editAlarmRule();
    void saveAlarmRule();
    void cancelEdit();
    void filterAlarmRecords();
    void editAlarmRecord();


private:
    // 界面组件
    QTableView *m_rulesTableView;
    QTableView *m_recordsTableView;
    QPushButton *m_addRuleButton;
    QPushButton *m_deleteRuleButton;
    QPushButton *m_editRuleButton;
    QPushButton *m_saveRuleButton;
    QPushButton *m_cancelButton;
    QLineEdit *m_deviceFilterEdit;
    QPushButton *m_filterButton;
    QComboBox *m_statusFilterCombo;
    QDateTimeEdit *m_startTimeFilter;
    QDateTimeEdit *m_endTimeFilter;
    QPushButton *m_editRecordButton;

    // 数据模型
    QSqlTableModel *m_rulesModel;
    QSqlRelationalTableModel *m_recordsModel;
    QSortFilterProxyModel *m_recordsProxyModel;

    // 状态变量
    bool m_isEditing;
    int m_editedRow;

    // 告警控制相关
    QMap<int, QDateTime> m_lastAlarmTimes; // 设备最近告警时间
    int m_alarmInterval; // 告警间隔(秒)
    QSettings *m_emailSettings; // 邮件配置

    // 初始化UI和数据
    void setupUI();
    void setupModels();
    void loadDeviceNames();
    void initEmailSettings();

    // 告警处理相关函数
    QList<QMap<QString, QVariant>> getAlarmRulesForDevice(int deviceId);
    bool checkCondition(const QMap<QString, QVariant> &rule, const DataPoint &data);
    void logAlarmRecord(int deviceId, const QString &content);
    bool isWithinAlarmInterval(int deviceId);
    void sendAlertNotification(int deviceId, const QString &message);

    void sendViaCommandLine(const QString &smtpServer, int port,
                                         const QString &username, const QString &password,
                                         const QString &recipient, const QString &content);

    bool checkEmailConfig() const;

    SqliteManage *m_pSqliteManage;
    LogClass *m_pLog;
    QString username;
};

#endif // WARNINGMANAGE_H
